/**
 * 场景协调器（重构版）
 * 
 * 改进：
 * 1. 只导出类，不导出实例
 * 2. 提供便捷的静态访问器
 * 3. 避免循环依赖
 * 4. 易于测试
 * 
 * @author AI Assistant
 * @date 2025-11-27
 */

import { Node, Prefab, instantiate, Vec3, find } from "cc";
import { resLoader } from "../../core/resload";
import { Log } from "../../core/logger/LoggerGlobal";

/**
 * 场景层级配置
 */
export interface LayerConfig {
    name: string;
    zIndex: number;
    description?: string;
}

/**
 * 预制体实例化选项
 */
export interface InstantiateOptions {
    position?: Vec3;
    parent?: Node;
    layerName?: string;
    name?: string;
}

/**
 * 场景协调器类
 */
export class SceneCoordinator {
    private static _instance: SceneCoordinator | null = null;
    
    private sceneRoot: Node | null = null;
    private layers: Map<string, Node> = new Map();
    private prefabCache: Map<string, Prefab> = new Map();
    private nodePool: Map<string, Node> = new Map();
    private _initialized: boolean = false;
    
    private readonly DEFAULT_LAYERS: LayerConfig[] = [
        { name: 'background', zIndex: -100, description: '背景层' },
        { name: 'game', zIndex: 0, description: '游戏对象层' },
        { name: 'effect', zIndex: 100, description: '特效层' },
        { name: 'ui', zIndex: 200, description: 'UI层' },
        { name: 'top', zIndex: 300, description: '顶层（调试等）' }
    ];
    
    private constructor() {}
    
    /**
     * 获取单例实例（懒加载）
     */
    static getInstance(): SceneCoordinator {
        if (!this._instance) {
            this._instance = new SceneCoordinator();
        }
        return this._instance;
    }
    
    /**
     * 便捷的静态访问器
     * 
     * 使用：SceneCoordinator.shared.init(node)
     */
    static get shared(): SceneCoordinator {
        return this.getInstance();
    }
    
    /**
     * 重置单例（主要用于测试）
     */
    static resetInstance(): void {
        if (this._instance) {
            this._instance.destroy();
            this._instance = null;
        }
    }
    
    // ... 其他方法保持不变 ...
    
    init(sceneRoot: Node, customLayers?: LayerConfig[]): void {
        if (this._initialized) {
            Log.scene.warn('已经初始化，跳过重复初始化');
            return;
        }
        
        if (!sceneRoot || !sceneRoot.isValid) {
            Log.scene.error('无效的场景根节点');
            return;
        }
        
        this.sceneRoot = sceneRoot;
        const layerConfig = customLayers || this.DEFAULT_LAYERS;
        this.createLayers(layerConfig);
        this._initialized = true;
        
        Log.scene.info('✅ 初始化完成', {
            sceneRoot: sceneRoot.name,
            layerCount: this.layers.size
        });
    }
    
    private createLayers(layerConfigs: LayerConfig[]): void {
        if (!this.sceneRoot) return;
        
        for (const config of layerConfigs) {
            let layer = this.sceneRoot.getChildByName(config.name);
            
            if (!layer) {
                layer = new Node(config.name);
                layer.setPosition(0, 0, config.zIndex);
                this.sceneRoot.addChild(layer);
            }
            
            this.layers.set(config.name, layer);
        }
    }
    
    getLayer(layerName: string): Node | null {
        const layer = this.layers.get(layerName);
        if (!layer) {
            Log.scene.warn('层级不存在，返回场景根节点', { layerName });
            return this.sceneRoot;
        }
        return layer;
    }
    
    destroy(): void {
        Log.scene.info('销毁场景协调器');
        this.clearAllLayers();
        this.prefabCache.clear();
        this.nodePool.clear();
        this.layers.clear();
        this.sceneRoot = null;
        this._initialized = false;
    }
    
    private clearAllLayers(): void {
        for (const layer of this.layers.values()) {
            layer.destroyAllChildren();
        }
    }
}

// ✅ 只导出类，不导出实例

/**
 * 使用方式：
 * 
 * 方式 1：完整写法
 * ```typescript
 * import { SceneCoordinator } from './SceneCoordinator';
 * const coordinator = SceneCoordinator.getInstance();
 * coordinator.init(sceneRoot);
 * ```
 * 
 * 方式 2：简洁写法（推荐）
 * ```typescript
 * import { SceneCoordinator } from './SceneCoordinator';
 * SceneCoordinator.shared.init(sceneRoot);
 * SceneCoordinator.shared.getLayer('game');
 * ```
 * 
 * 方式 3：本地变量（高频使用）
 * ```typescript
 * import { SceneCoordinator } from './SceneCoordinator';
 * const scene = SceneCoordinator.shared;
 * scene.init(sceneRoot);
 * scene.getLayer('game');
 * scene.createNode('player');
 * ```
 */

